import sys
from pathlib import Path

# 改变路径
current_folder = Path(__file__).absolute().parent
father_folder = str(current_folder.parent)
sys.path.append(father_folder)

from typing import List
import requests
from utils.JSON的输入和输出 import 写入json, 读取json

deckrecipe = 读取json('output/IDS_To_JSON/IDS_DECKRECIPE.json')


def getIndexOfShortestStr(list: List[str]) -> int:
    '''
    获取最短的字符串的索引
    '''
    index = 0
    for i, str in enumerate(list):
        if len(str) < len(list[index]):
            index = i
    return index


def getZhWithApi(name_jp: str) -> str:
    if name_jp.startswith('<'): return name_jp
    '''
    使用API查询中文名字和中文描述
    '''
    # 需要替换的符号
    char_need_replace = [['.', '．'], [' ', '　'], ['－', '－']]
    for char in char_need_replace:
        name_jp = name_jp.replace(char[1], char[0])
    url = "https://tools.kooriookami.top/api/yugioh/card"
    params = {"name": name_jp, 'lang': 'jp'}
    res = requests.get(url=url, params=params)
    name_zh = f"中文名字未知，日文名是{name_jp}"
    desc_zh = f"中文描述未知，日文名是{name_jp}"
    if res.status_code == 200 and len(res.json()['data']):
        index = getIndexOfShortestStr(
            [item['name'] for item in res.json()['data']])
        # 拿到日文名字对应id
        id = res.json()['data'][index]['id']  # 名字最短的index对应的id
        # 拿到中文名字和描述
        url = f"https://tools.kooriookami.top/api/yugioh/card/{id}"
        res = requests.get(url=url)
        if res.status_code == 200:
            name_zh = res.json()['data']['name']
            desc_zh = res.json()['data']['desc']
    return name_zh


def getWordsInSentence(sentence: str) -> List[str]:
    words_in_source = []
    is_in_word = False
    for char in sentence:
        if is_in_word:
            words_in_source[-1] += char
        if char == '「':
            words_in_source.append('')
            is_in_word = True
        elif char == '」':
            words_in_source[-1] = words_in_source[-1][:-1]
            is_in_word = False
    return words_in_source


def getAllIndxOfSpecialChar(sentence: str) -> List[int]:
    '''
    获取所有特殊字符的索引
    '''
    indexs = []
    for i, char in enumerate(sentence):
        if char in ['「', '」']:
            indexs.append(i)
    return indexs


for index, item in enumerate(deckrecipe):
    line = index * 5 + 1
    if (line) >= 2536:
        print(line)
        words_in_source = getWordsInSentence(item['source'])
        words_in_trans = getWordsInSentence(item['trans'])
        transed_words_in_source = [
            getZhWithApi(word) for word in words_in_source
        ]
        trans_splited = ['']
        all_indx = getAllIndxOfSpecialChar(item['trans'])
        flag = True
        for indx in range(len(item['trans'])):
            if flag:
                trans_splited[-1] += item['trans'][indx]
            if indx in all_indx:
                if item['trans'][indx] == '「':
                    flag = False
                    trans_splited[-1] = trans_splited[-1][:-1]
                elif item['trans'][indx] == '」':
                    flag = True
                    trans_splited.append('')

        zh = ''
        for i in range(len(transed_words_in_source)):
            try:
                zh += trans_splited[i] + f'「{transed_words_in_source[i]}」'
            except:
                pass
        zh += trans_splited[-1]
        item['trans'] = zh
        # break
        写入json(deckrecipe, 'output/IDS_To_JSON/IDS_DECKRECIPE.json')
